package flexserverlib.delegates;

import flexserverlib.messaging.services.messaging.adapters.support.MailMessage;
import flexserverlib.services.IPOP3Service;
import flexserverlib.services.POP3Service;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.ArrayList;

/**
 * @author Andrew Powell - Universal Mind - andrew.powell@universalmind.com
 */
@Service("pop3Service")
@RemotingDestination(channels = {"my-amf", "my-secure-amf"})
public class POP3Delegate {

    public POP3Delegate() {
    }

    public ArrayList<MailMessage> getMessages(String user, String password, String server) {
        ArrayList<MailMessage> messages = new ArrayList<MailMessage>();

        try {
            IPOP3Service svc = new POP3Service(server, user, password);
            svc.connect();
            Message[] raw = svc.getMessages();
            System.out.println(raw.length);
            for (Message msg : raw) {
                MailMessage mmsg = new MailMessage();
                mmsg.sender = msg.getFrom()[0].toString();
                mmsg.subject = msg.getSubject();
                mmsg.recipient = msg.getRecipients(MimeMessage.RecipientType.TO)[0].toString();
                if (msg.getContent().getClass().equals(String.class)) mmsg.body = (String) msg.getContent();
                else {
                    MimeMultipart mp = (MimeMultipart) msg.getContent();
                    for (int i = 0; i < mp.getCount(); i++) {
                        mmsg.body += mp.getBodyPart(i).getContent().toString();
                    }
                    mmsg.body = msg.getContent().toString();
                }
                messages.add(mmsg);

            }
            svc.disconnect();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return messages;

    }
}
